﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Patrick van der Velde
 * Marcus Cuda
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#region Using Directives

using System;
using System.Collections;
using System.Globalization;
using System.IO;
using dnAnalytics.Properties;

#endregion Using Directives

namespace dnAnalytics.LinearAlgebra.IO
{
    /// <summary>
    /// Writes an <see cref="Matrix"/> to a DenseMatrix Market formatted file.
    /// </summary>
    /// <remarks>see <a href="http://math.nist.gov/MatrixMarket/formats.html">http://math.nist.gov/MatrixMarket/formats.html</a> for more information.</remarks>
    public class MatrixMarketWriter : SingleMatrixWriter
    {
        private readonly double epsilon = Double.Epsilon;
        private readonly ExchangeFormat exchangeFormat;
        private readonly DataType type;


        /// <summary>
        /// Constructs a <b>MatrixMarketWriter</b> with the given <see cref="ExchangeFormat"/> and <see cref="DataType"/>.
        /// </summary>
        /// <param name="format">The exchange format to use.</param>
        /// <param name="type">The data type to use.</param>
        /// <exception cref="NotSupportedException">If <paramref name="type"/> is a <see cref="DataType.Complex"/>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="format"/> is a <see cref="ExchangeFormat.Array"/> and 
        /// <paramref name="type"/> is a <see cref="DataType.Pattern"/>. They are incompatible options.</exception>
        public MatrixMarketWriter(ExchangeFormat format, DataType type)
        {
            if (type == DataType.Complex)
            {
                throw new NotSupportedException(Resources.ComplexNotSupported);
            }

            if (format == ExchangeFormat.Array && type == DataType.Pattern)
            {
                throw new ArgumentException(Resources.InvalidQualifierCombination);
            }
            exchangeFormat = format;
            this.type = type;
        }

        /// <summary>
        /// Constructs a <b>MatrixMarketWriter</b> with the given <see cref="ExchangeFormat"/> and <see cref="DataType"/>.
        /// </summary>
        /// <param name="format">The exchange format to use.</param>
        /// <param name="type">The data type to use.</param>
        /// <param name="epsilon">Only used with <see cref="DataType.Pattern"/>. Determines which values are not equal to zero, 
        /// <b>System.Math.Abs(value) > epsilon;</b></param>
        /// <remarks><see cref="DataType.Complex"/> is not supported.</remarks>
        public MatrixMarketWriter(ExchangeFormat format, DataType type, double epsilon)
            : this(format, type)
        {
            this.epsilon = epsilon;
        }

        /// <summary>
        /// Writes a matrix to the given TextWriter with the Array layout.
        /// </summary>
        /// <param name="matrix">The matrix to write.</param>
        /// <param name="writer">The TextWriter to use.</param>
        /// <param name="format">The number format to use.</param>
        private void WriteArray(Matrix matrix, TextWriter writer, string format)
        {
            writer.Write(matrix.Rows);
            writer.Write(" ");
            writer.Write(matrix.Columns);
            writer.Write(Environment.NewLine);

            for (int j = 0; j < matrix.Columns; j++)
            {
                for (int i = 0; i < matrix.Rows; i++)
                {
                    if (type == DataType.Real)
                    {
                        writer.Write(matrix[i, j].ToString(format, CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        writer.Write(((int) matrix[i, j]).ToString(format, CultureInfo.InvariantCulture));
                    }
                    writer.Write(Environment.NewLine);
                }
            }
        }

        /// <summary>
        /// Writes a matrix to the given TextWriter with a coordinate layout, but doesn't
        /// write out the data (Pattern data type).
        /// </summary>
        /// <param name="matrix">The matrix to write.</param>
        /// <param name="writer">The TextWriter to use</param>
        private void WriteCoordinatePattern(Matrix matrix, TextWriter writer)
        {
            ArrayList data = new ArrayList();
            for (int i = 0; i < matrix.Rows; i++)
            {
                for (int j = 0; j < matrix.Columns; j++)
                {
                    if (System.Math.Abs(matrix[i, j]) > epsilon)
                    {
                        string item = (i + 1) + " " + (j + 1);
                        data.Add(item);
                    }
                }
            }
            writer.Write(matrix.Rows);
            writer.Write(" ");
            writer.Write(matrix.Columns);
            writer.Write(" ");
            writer.Write(data.Count);
            writer.Write(Environment.NewLine);
            foreach (string item in data)
            {
                writer.WriteLine(item);
            }
        }

        /// <summary>
        /// Writes a matrix to the given TextWriter with a coordinate layout.
        /// </summary>
        /// <param name="matrix">The matrix to write.</param>
        /// <param name="writer">The TextWriter to use</param>
        /// <param name="format">The number format to use.</param>
        private void WriteCoordinate(Matrix matrix, TextWriter writer, string format)
        {
            writer.Write(matrix.Rows);
            writer.Write(" ");
            writer.Write(matrix.Columns);
            writer.Write(" ");
            writer.Write(matrix.Columns*matrix.Rows);
            writer.Write(Environment.NewLine);

            for (int i = 0; i < matrix.Rows; i++)
            {
                for (int j = 0; j < matrix.Columns; j++)
                {
                    writer.Write((i + 1));
                    writer.Write(" ");
                    writer.Write((j + 1));
                    writer.Write(" ");
                    if (type == DataType.Real)
                    {
                        writer.Write(matrix[i, j].ToString(format, CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        writer.Write(((int) matrix[i, j]).ToString(format, CultureInfo.InvariantCulture));
                    }
                    writer.Write(Environment.NewLine);
                }
            }
        }

        private void WriteHeader(TextWriter writer)
        {
            writer.Write("%%MatrixMarket matrix ");
            if (exchangeFormat == ExchangeFormat.Array)
            {
                writer.Write("array ");
            }
            else
            {
                writer.Write("coordinate ");
            }

            switch (type)
            {
                case DataType.Real:
                    writer.Write("real ");
                    break;
                case DataType.Integer:
                    writer.Write("integer ");
                    break;
                case DataType.Pattern:
                    writer.Write("pattern ");
                    break;
            }
            writer.Write("general");
            writer.Write(Environment.NewLine);
        }


        /// <summary>
        /// Does the actual writing of the matrix.
        /// </summary>
        /// <param name="matrix">The matrix to serialize.</param>
        /// <param name="writer">The <see cref="TextWriter"/> to write the matrix to.</param>
        /// <param name="format">The format for the new matrix.</param>
        protected override void DoWriteMatrix(Matrix matrix, TextWriter writer, string format)
        {
            if (matrix == null)
            {
                throw new ArgumentNullException("matrix", Resources.NullParameterException);
            }
            if (writer == null)
            {
                throw new ArgumentNullException("writer", Resources.NullParameterException);
            }
            WriteHeader(writer);
            if (exchangeFormat == ExchangeFormat.Array)
            {
                WriteArray(matrix, writer, format);
            }
            else
            {
                if (type == DataType.Pattern)
                {
                    WriteCoordinatePattern(matrix, writer);
                }
                else
                {
                    WriteCoordinate(matrix, writer, format);
                }
            }
        }
    }
}